package GameElements;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;

import javax.swing.ImageIcon;
import javax.swing.JLabel;


import Utils.ImageUtils;

public class Tile 
{
	public final static int nothing=0, castle=1, street=2, farm=3, cloister=4;
	public final static int n0=0, n1=1, n2=2, e0=3, e1=4, e2=5, s0=6, s1=7, s2=8, w0=9, w1=10, w2=11, c=12;
	private ImageIcon imgTile;
	private JLabel imgLabel;
	private int north;
	private int east;
	private int south;
	private int west;
	private int center = nothing;
	private int[] links;
	private Pawn[] pawn;

	public Tile(String imgName, int north, int east, int south, int west, int[] links)
	{
		this.north = north;
		this.east = east;
		this.south = south;
		this.west = west;
		this.links = links;
		pawn = new Pawn[13];
		imgTile = new ImageIcon(imgName);
		imgLabel = new JLabel(imgTile);
	}
	
	public Tile(String imgName, int north, int east, int south, int west, int center, int[] links)
	{
		this.north = north;
		this.east = east;
		this.south = south;
		this.west = west;
		this.center = center;
		this.links = links;
		pawn = new Pawn[13];
		imgTile = new ImageIcon(imgName);
		imgLabel = new JLabel(imgTile);
	}
	
	public void rotate90()
	{ 
		//rotation des coins cardinaux
		int newNorth = west;
		int newEast = north;
		int newSouth = east;
		int newWest = south;
		
		north = newNorth;
		east = newEast;
		south = newSouth;
		west = newWest;
		
		//rotation des liens
		int[] newLinks = new int[12];
		for(int i=0; i<links.length; i++)
			newLinks[(i+3)%links.length]= links[i];
		links = newLinks;
		
		//rotation des positions des pions
		Pawn[] newPawn = new Pawn[13];
		for(int i=0; i<pawn.length-1; i++)
			newPawn[(i+3)%(pawn.length - 1)]= pawn[i];
		newPawn[12]= pawn[12];
		pawn = newPawn;		
		
		//rotation d'imgTile
		imgTile = new ImageIcon(ImageUtils.rotateImage(imgTile.getImage(), 90));
		repaintImg();
	}	

	
	public JLabel getImgLabel(){		
		return imgLabel;
	}
	public int getNorth() {
		return north;
	}
	public int getEast() {
		return east;
	}
	public int getSouth() {
		return south;
	}
	public int getWest() {
		return west;
	}
	public int getCenter() {
		return center;
	}
	public int[] getLinks() {
		return links;
	}
	public Pawn[] getPawn() {
		return pawn;
	}
	
	public void setPawn(Pawn p, int index) {
		pawn[index] = p;
		repaintImg();
	}
	
	private void repaintImg()
	{
		Image bufferedImg = new BufferedImage(imgTile.getIconWidth(), imgTile.getIconHeight(), BufferedImage.TYPE_INT_RGB);
		Graphics2D g2d = (Graphics2D)bufferedImg.getGraphics();
		g2d.drawImage(imgTile.getImage(), 0, 0, null);
		for(int i=0; i< pawn.length; i++)
			if(pawn[i] != null)
				g2d.drawImage(pawn[i].getImg().getImage(), 0, i * 3, null);		
		imgLabel = new JLabel(new ImageIcon(bufferedImg));
	}
}
